import datetime
import time
import traceback

from absl import app, flags

from coin.strategy.kr_hard_arb.arb_info import create_arb_info_general
from coin.strategy.kr_hard_arb.util import *

FLAGS = flags.FLAGS

flags.DEFINE_string('currency', 'BTC', 'Currency, default is BTC.')

flags.DEFINE_string('exchanges', None, 'Exchange list separated by comma.')

flags.DEFINE_string('key_files', None, 'Key file list by comma.')

flags.DEFINE_string('config_filename', None, 'Configuration file.')

flags.DEFINE_bool('dry_run', False, 'dry_run')


def update(info, currency):
  try:
    print()
    execute_thread_runners([ThreadRunner(exch.order.query_balance) for exch in info.exchs],
                           "Collecting %s Data" % currency)
  except KeyboardInterrupt:
    raise
  except Exception as exc:
    print("A problem detected. Try again")
    print(exc)
    traceback.print_exc()


def test(info):
  for exch in info.exchs:
    print(exch.order.get_balance_cached() is not None)


def main(_):
  currency = FLAGS.currency
  assert currency == "BTC", 'balance\'s currency must be BTC'
  assert FLAGS.exchanges, 'exchanges not specified.'
  assert FLAGS.key_files, 'key_files not specified'

  info = create_arb_info_general(currency,
                                 FLAGS.exchanges.split(","),
                                 FLAGS.key_files.split(","),
                                 FLAGS.config_filename)

  verbose_every_n = 10
  verbose_count = 0

  while True:
    time.sleep(1)
    print()
    print(datetime.datetime.now())
    print("Checking...")
    update(info, currency)
    test(info)
    verbose_count += 1


if __name__ == '__main__':
  app.run(main)
